package com.foodchain.service;

import com.foodchain.entity.SystemSetting;
import com.foodchain.repository.SystemSettingRepository;
import com.foodchain.util.Misc;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class SystemSettingService {

    @Resource
    private SystemSettingRepository repository;

    public SystemSetting getById(String id) { return repository.getOne(id); }

    @Transactional
    public void updateKeyValue(String value, String id) {
        repository.updateKeyValue(value, id);
    }

    /**
     * @param: [page, size];
     * @return: org.springframework.data.domain.Page<com.foodchain.entity.SystemSetting>;
     * @Description: 不带条件分页查询;
     */
    public Page<SystemSetting> findSystemSettingNoCriteria(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");

        return repository.findAll(pageable);
    }

    /**
     * @param: [page, size, SystemSetting];
     * @return: org.springframework.data.domain.Page<com.foodchain.entity.SystemSetting>;
     * @Description: 带条件的分页查询;
     */
    public Page<SystemSetting> findSystemSettingCriteria(Integer page, Integer size, SystemSetting setting) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");

        return repository.findAll((Specification<SystemSetting>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            if (Misc.isNotEmpty(setting.getKey()))
                list.add(criteriaBuilder.equal(root.get("key").as(String.class), setting.getKey()));

            Predicate[] predicateArray = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(predicateArray));
        }, pageable);
    }

    public SystemSetting findByKey(String key) {
        return repository.findByKey(key);
    }
}
